package mud

import org.springframework.transaction.annotation.Transactional

import com.unknown.world.Exit
import com.unknown.world.Room

class RoomService {
	
	Room findById(def id){
		return Room.findByEntityId( id )
	}
	
	List<Room> findAll(){
		return Room.list()
	}

	Room createExit(def params){
		Room room = findById(params.id)
		validateNotNull(room)
		
		Room neighbor = null;
		if( params.roomId ){
			neighbor = findById(params.roomId)
			validateNotNull(room)
		}else{
			neighbor = new Room(name:'New Room')
			save(neighbor)
		}
		
		Exit exit = new Exit(name:params.direction, roomId:neighbor.id, row:params.int('row'), col:params.int('col'))
		if(!room.exits) room.exits = []
		room.exits.add(exit)
		save(room)
		
		return neighbor;
	}
	
	Room save(Room room){
		if(!room.save()){
			room.errors.each {
				println it	
			}
			throw new RuntimeException("Save failed")
		}
		return room
	}
	
	void delete(Room room){
		room.delete()
	}
	
	def validateNotNull(def object){
		if( !object ) throw NotFoundException()
	}
	
}
